package com.bnzj.cloud.business.core.persistence.repository;

import com.bnzj.cloud.business.core.persistence.entity.SysRole;
import com.bnzj.core.persistence.repository.BaseRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

@Repository
public interface SysRoleRepository extends BaseRepository<SysRole, Long> {

    /**
     * 系统初始化专用，非懒加载模式
     *
     * @param account
     * @return
     */
    @Query(value = "select s from SysRole s LEFT JOIN FETCH s.roleResourceList rr LEFT JOIN FETCH rr.resource rs LEFT JOIN FETCH rs.children where s.enabled = 1")
    public Set<SysRole> eagerlyFindAll();

    @Query(value = "from SysRole where enabled = 1 and code=?1")
    public SysRole findByCode(String code);

    /**
     * @return
     */
    @Query(value = "select code from SysRole where enabled = 1")
    public List<String> findAllCode();

    /**
     * @param account
     * @return
     */
    @Query(value = "select DISTINCT r.code from bnz_sys_role r, bnz_sys_role_user ru, bnz_sys_user u where r.enabled = 1 and r.id = ru.role_id and ru.user_id = u.id and u.account = ?1", nativeQuery = true)
    public List<String> getAllRoleCodeByAccount(String account);

    @Modifying
    @Query(value = "update bnz_sys_role set enabled =?1 WHERE id = ?2", nativeQuery = true)
    public void updateEnabled(Short type,Long id);
}
